
from flask import Flask, render_template, request, jsonify, Blueprint
import requests
import json
import re

# 创建蓝图，蓝图的名称为包的名称kozi_page
kozi_page = Blueprint('kozi_page', __name__)

BOT_ID = "7448925358177058856"
API_TOKEN = "pat_yfgiLTW3ltGBN8bnpoWPpiXzwmmbtNBXUFGTdh6Dy0Em2FdFvDARd7KdUQibqWvO"
BASE_URL = "https://api.coze.cn/v3"

@kozi_page.route('/')
def kozi():
    return render_template('kozi.html')

@kozi_page.route('/send_message', methods=['POST'])
def send_message():
    user_message = request.form['message']
    url = f"{BASE_URL}/chat"
    headers = {
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    }
    data = {
        "bot_id": BOT_ID,
        "user_id": "123",
        "stream": True,
        "auto_save_history": True,
        "additional_messages": [
            {
                "role": "user",
                "content": user_message,
                "content_type": "text"
            }
        ]
    }

    response = requests.post(url, headers=headers, json=data)
    reply = ""

    for lines in response.iter_lines():
        if not lines:
            continue
        lines = lines.decode('utf-8')

        reply = reply + lines

    data = reply
    # 提取并解析长字符串中的 JSON 数据
    pattern = r'\{.*?\}'

    # 提取所有符合 JSON 模式的子字符串
    json_strings = re.findall(pattern, data)

    # 提取文本信息并去除重复项
    seen = set()
    unique_contents = []

    for json_str in json_strings:
        try:
            json_data = json.loads(json_str)
            if 'content' in json_data:
                content = json_data['content']
                if content not in seen:
                    seen.add(content)
                    unique_contents.append(content)
        except json.JSONDecodeError:
            pass

    test = ""
    # 输出结果
    for content in unique_contents:
        clean_content = re.sub(r'\\"', '"', content)
        clean_content = re.sub(r'\\n', '\n', clean_content)
        test = test + clean_content + "\n"
        # print(clean_content)

    print(test)
    return jsonify({"test": test})



